<template>
  <Row class="page-wrap" :gutter="12">
    <Col :span="12" style="height: 280px">
      <div class="title"> <span class="text">params</span></div>
      <a-form
        :model="formState"
        name="basic"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        :rules="rules"
        @finish="onFinish"
        @finish-failed="onFinishFailed"
      >
        <!-- <a-form-item label="AES_KEY" name="AES_KEY">
          <a-input v-model:value="formState.AES_KEY" :maxlength="48" />
        </a-form-item> -->

        <a-form-item label="CREATION_DATE" name="CREATION_DATE">
          <!-- <a-input v-model:value="formState.CREATION_DATE" /> -->
          <a-date-picker v-model:value="formState.CREATION_DATE" format="YYYY-MM-DD(DDMMYY)" valueFormat="DDMMYY" />
        </a-form-item>

        <a-form-item label="PRODUCT_CODE" name="PRODUCT_CODE"><a-input v-model:value="formState.PRODUCT_CODE" :maxlength="44" /> </a-form-item>
        <a-form-item label="UID" name="UUID"><a-input v-model:value="formState.UUID" :maxlength="25" clearable /> </a-form-item>

        <a-form-item :wrapper-col="{ offset: 6, span: 4 }">
          {{ source }}
          <a-button style="float: left" type="primary" html-type="submit">执行</a-button>
        </a-form-item>
      </a-form>
    </Col>
    <Col :span="12" style="height: 280px">
      <div class="title">
        <span class="text">result</span>
        <span v-if="result">time：{{ time }}</span>
      </div>
      <!-- <div><span>AESText：</span>{{ result.AESText }}</div>
      <div><span>PLAIN_TEXT：</span>{{ result.PLAIN_TEXT }}</div>
      <div><span>RC4Code_TEXT：</span>{{ result.RC4Code_TEXT }}</div> -->
      <div style="height: 210px"> <CodeEditor v-model:value="result" mode="application/json" readonly /></div>
    </Col>
    <Col :span="24" :flex="1" style="height: calc(100% - 280px)">
      <div class="title">
        <span class="text">log</span>

        <a-button type="danger" @click="delClick">删除最新一个</a-button>
        <a-button @click="exportFile" style="margin-left: 12px">创建工作表</a-button>
        <input type="file" @change="handleFileUpload" />
      </div>

      <BasicTable v-bind="config" :dataSource="Aes4DeleoList">
        <template #operation="{ record }">
          <a-button type="primary" size="small" @click="copyClick(record)">复制</a-button>

          <!-- <a-button type="danger" size="small" @click="delClick(record)" style="margin-left: 12px">删除</a-button> -->
        </template>
      </BasicTable>
    </Col>
  </Row>
</template>
<script lang="ts" setup>
  import { Row, Col } from 'ant-design-vue';
  import { reactive, ref } from 'vue';
  import { getAes4Deleo } from './ToolTest.api';
  import { CodeEditor } from '/@/components/CodeEditor';
  import { createLocalStorage } from '/@/utils/cache';
  import { BasicTable, BasicColumn } from '/@/components/Table';
  import dayjs from 'dayjs';
  import { utils, writeFileXLSX, read } from 'xlsx';
  import { useClipboard } from '@vueuse/core';
  // import { saveOrUpdate } from '../management/DeleoAesCipher.api';
  import { encode } from './a';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { debounce } from 'lodash';
  const message = useMessage();
  const source = ref('');
  const { copy, isSupported } = useClipboard({ source });
  interface FormState {
    UUID: string;
    CREATION_DATE: string;
    AES_KEY: string;
    PRODUCT_CODE: string;
  }
  const handleFileUpload = (event) => {
    const file = event.target.files[0];
    const reader = new FileReader();
    reader.onload = (e: any) => {
      const data = new Uint8Array(e.target.result);
      const workbook = read(data, { type: 'array' });
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      const excelData: string[][] = utils.sheet_to_json(worksheet, { header: 1 });
      console.log(excelData, 'excelDataexcelData');
      excelData.forEach((item, index) => {
        const encodeData = encode(item[0]);
        item.push('260224', encodeData.data, encodeData.text);
        item.unshift(String(index + 1), dayjs().format('YYYY-MM-DD HH:mm:ss'));
      });

      createSheet(excelData);
    };
    reader.readAsArrayBuffer(file);
  };

  const rules = {
    UUID: {
      required: true,
      trigger: 'blur',
      validator(_, value, callback) {
        if (value.length == 0) {
          callback('请输入UUID');
        } else {
          callback();
        }
        // if (!/^[0-9A-Fa-f]+$/.test(value)) {
        //   callback('UUID是十六进制字符串');
        // } else {
        //   callback();
        // }
      },
    },
    AES_KEY: {
      required: true,
      trigger: 'blur',
      validator(_, value, callback) {
        if (value.length == 0) {
          callback('请输入AES_KEY');
          return;
        }
        if (value.length !== 48 || !/^[0-9A-Fa-f]+$/.test(value)) {
          callback('AES_KEY是长度为48位的十六进制字符串');
        } else {
          callback();
        }
      },
    },
    CREATION_DATE: [{ required: true, message: '请选择日期!' }],
    PRODUCT_CODE: {
      required: true,
      trigger: 'blur',
      validator(_, value, callback) {
        if (value.length == 0) {
          callback('请输入AES_KEY');
          return;
        }
        const splitVal = value.split('(create_date)');

        if (value.length !== 44 || splitVal.length !== 2 || !/^[0-9A-Fa-f]+$/.test(splitVal[0]) || !/^[0-9A-Fa-f]+$/.test(splitVal[1])) {
          callback('请输入正确格式的PRODUCT_CODE,格式为：xxxxxxxxxxxxxxxx(create_date)xxxxx');
        } else {
          callback();
        }
      },
    },
  };

  const formState = reactive<FormState>({
    UUID: '687DD2EF500104E0',
    CREATION_DATE: '260224',
    AES_KEY: '6433432C713528557A25715E78573950353437583F675372',
    // PRODUCT_CODE: '45464D46502D00010001000001(create_date)47135',
    PRODUCT_CODE: '44454C454F2D00010001000001(create_date)3F882',
  });
  const lStorage = createLocalStorage();
  const Aes4DeleoList = ref<any[]>(lStorage.get('Aes4DeleoList') ?? []);
  // Aes4DeleoList.value[133] = Aes4DeleoList.value[0];
  // Aes4DeleoList.value[133].index = 1368;
  // set(Aes4DeleoList.value);

  Aes4DeleoList.value.forEach((element) => {
    let index = 0;
    Aes4DeleoList.value.forEach((item) => {
      if (item.UUID === element.UUID) {
        index++;
      }
    });
    if (index === 2) {
      console.log(element, 'Aes4DeleoList');
    }
  });
  console.log(new Set(Aes4DeleoList.value.map((item) => item.UUID)));
  // console.log(Aes4DeleoList.value[64], Aes4DeleoList.value[65], 'Aes4DeleoList');
  const time = ref('');
  const result = ref<any>('');
  const onFinish = debounce(
    (values: any) => {
      values.UUID = values.UUID.replace(':', '');
      const val = { ...values };
      val.UUID = values.UUID.replaceAll(':', '');
      formState.UUID = val.UUID;
      console.log('values.UUID', encode(values.UUID));
      getAes4Deleo(val).then((res) => {
        const AESText = res.AESText;
        time.value = dayjs().format('YYYY-MM-DD HH:mm:ss');
        const str = AESText.replaceAll(' ', '')
          .match(/.{1,2}/g)
          .reduce((pre, item) => {
            return pre + String.fromCharCode(parseInt(item, 16));
          }, '');
        result.value = [AESText, str];
        const index = Aes4DeleoList.value.length + 1;
        Aes4DeleoList.value.unshift({
          index,
          time: time.value,
          UUID: formState.UUID,
          CREATION_DATE: formState.CREATION_DATE,
          AESText: AESText,
          AESTextFormat: str,
        });

        message.createMessage.success(Aes4DeleoList.value.length);
        // saveOrUpdate(
        //   {
        //     sysOrgCode: index,
        //     uuid: formState.UUID,
        //     createDate: formState.CREATION_DATE,
        //     aesText: AESText,
        //   },
        //   false
        // );
        set(Aes4DeleoList.value);
      });
    },
    1500,
    { leading: true, trailing: false }
  );
  function set(data) {
    lStorage.set('Aes4DeleoList', data);
    Aes4DeleoList.value = lStorage.get('Aes4DeleoList');
  }

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  //定义表格列
  const columns: BasicColumn[] = [
    {
      title: 'index',
      align: 'center',
      width: 70,
      dataIndex: 'index',
    },
    {
      title: '执行时间',
      align: 'center',
      width: 160,
      dataIndex: 'time',
    },

    {
      title: 'UUID',
      align: 'center',
      width: 160,
      dataIndex: 'UUID',
    },
    {
      title: 'CREATION_DATE',
      width: 160,
      align: 'center',
      dataIndex: 'CREATION_DATE',
    },

    {
      title: 'AESText',
      align: 'center',
      dataIndex: 'AESText',
      customRender: ({ text }) => text,
    },

    {
      title: 'AESTextFormat',
      align: 'center',
      dataIndex: 'AESTextFormat',
      customRender: ({ text }) => text,
    },
    {
      title: '操作',
      width: 80,
      align: 'center',
      // defaultHidden: true,
      slots: { customRender: 'operation' },
    },
    {
      title: 'index',
      align: 'center',
      width: 70,
      dataIndex: 'index',
    },
  ];
  //表格配置
  const config: any = {
    canResize: false,
    bordered: true,
    size: 'small',
    columns,
  };

  const exportFile = () => {
    createSheet(Aes4DeleoList.value);
  };
  const createSheet = (data, sheetName = dayjs().format('YYYY-MM-DD HH：mm：ss')) => {
    // 创建一个工作簿 workbook
    const workBook = utils.book_new();
    // 创建工作表 worksheet
    // json_to_sheet 	是将【由对象组成的数组】转化成sheet
    // aoa_to_sheet  	是将【一个二维数组】转化成 sheet
    // table_to_sheet  	是将【table的dom】直接转成sheet
    // 这里我们使用 json_to_sheet
    const workSheet = utils.json_to_sheet(data);
    // 将工作表放入工作簿中
    // utils.book_append_sheet(workbook, worksheet, name, true);
    utils.book_append_sheet(workBook, workSheet, 'Data');
    // 生成数据保存
    writeFileXLSX(workBook, `${sheetName}.xlsx`, {
      bookType: 'xlsx',
    });
  };
  const copyClick = (record) => {
    if (isSupported) {
      copy(record.AESTextFormat);
      message.createMessage.success('复制成功：' + record.AESTextFormat);
    } else {
      message.createMessage.error('复制失败，浏览器禁止此网站使用剪贴板功能！');
    }

    // 创建一个临时的文本输入框
    const tempInput = document.createElement('input');
    tempInput.value = record.AESTextFormat;
    document.body.appendChild(tempInput);

    // 选中临时文本输入框的内容
    tempInput.select();
    tempInput.setSelectionRange(0, 99999); /* 兼容移动端 */

    // 执行复制命令
    document.execCommand('copy');

    // 移除临时文本输入框
    document.body.removeChild(tempInput);

    // 提示复制成功
    message.createMessage.success('复制成功：' + record.AESTextFormat);
  };
  const delClick = () => {
    Aes4DeleoList.value.shift();
    set(Aes4DeleoList.value);
  };
</script>
<style lang="less" scoped>
  .title {
    padding: 15px;
    > .text {
      font-weight: bold;
      font-size: 14px;
      padding-right: 20px;
    }
  }
  .page-wrap {
    height: 100%;
    padding: 6px 12px;
    > :deep(.ant-col) {
      background: #fff;
      border: 1px solid #eee;
    }
  }
</style>
